package com.gopay.cron.event.handler;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.gopay.common.datasource.DBType;
import com.gopay.common.datasource.DbContextHolder;
import com.gopay.common.domain.report.Event;
import com.gopay.common.event.EventState;
import com.gopay.common.event.handler.EventHandler;
import com.gopay.common.report.dao.MqEventInfoDAO;
import com.gopay.cron.service.trans.ReportConsoleTransQueryService;

@Service(value = "deleteEventDefaultHandler")
public class DeleteEventDefaultHandler implements EventHandler {

    @Resource
    private ReportConsoleTransQueryService reportConsoleTransQueryService;

    @Resource(name="mqEventInfoDAO")
    private MqEventInfoDAO mqEventInfoDAO;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class, RuntimeException.class })
    public void handler(Event e) {
        Map<String, Object> map =StringUtils.isNotBlank(e.getSnapshot())? (Map<String, Object>) JSONObject.parse(e.getSnapshot()):new HashMap<String, Object>();
        if(StringUtils.isNotBlank(e.getGopayOrderId())){
            map.put("gopayOrderId", e.getGopayOrderId());
        }
        
        DbContextHolder.setDbType(DBType.DS_REPORT.value);

        
        String gopayOrderId = (String) map.get("gopayOrderId");
        this.deleteReportConsoleTransQuery(gopayOrderId);
        Event result = mqEventInfoDAO.find(Event.class, e.getId());
        if (null != result) {
            result.setStat(EventState.SUCCESS.value);
            mqEventInfoDAO.update(result);
        }
    }

    private void deleteReportConsoleTransQuery(String gopayOrderId) {
        reportConsoleTransQueryService.deleteByGoPayOrderId(gopayOrderId);
    }

}
